<template>
  <el-form-item
    v-for="(item, key, i) in props.keys"
    :key="i"
    :prop="required ? key : ''"
  >
    <el-select
      filterable
      :style="{ width: width }"
      v-model="model[key]"
      :placeholder="i === 0 ? '省' : i === 1 ? '市' : '区'"
      @change="handleChange(key, i)"
    >
      <el-option
        v-for="item in i === 0 ? provinceList : i === 1 ? cityList : countyList"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
  </el-form-item>
</template>

<script lang="ts" setup>
const props = defineProps({
  form: {
    type: Object,
  },
  width: {
    type: String,
    default: '120px',
  },
  getData: {
    type: Function,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  keys: {
    type: Object,
  },
  required: {
    type: Boolean,
    default: false,
  },
})
const emit = defineEmits(['update:form'])
const model = ref({ ...props.form })
watch(
  () => props.form,
  (val) => {
    model.value = { ...val }
  },
  { deep: true }
)
const provinceList = ref([])
const cityList = ref([])
const countyList = ref([])
const keys = Object.keys(props.keys)

const getList = (id, name) => {
  props.getData({ data: id }).then((res) => {
    let data = res.data
    switch (name) {
      case 0:
        provinceList.value = data
        break
      case 1:
        cityList.value = data
        break
      case 2:
        countyList.value = data
        break
      default:
        break
    }
  })
}
const handleChange = (e, i) => {
  if (i < 2) {
    if (i === 0) {
      model.value[keys[1]] = ''
      model.value[keys[2]] = ''
    } else if (i === 1) {
      model.value[keys[2]] = ''
    }
    getList(model.value[e], i + 1)
  }
  emit('update:form', { ...props.form, ...model.value })
}
onMounted(() => {
  getList(0, 0)
  if (model.value.communityId) {
    getList(model.value[keys[0]], 1)
    getList(model.value[keys[1]], 2)
  }
})
</script>

<style lang="less" scoped></style>
